import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';

function userNameValidator(control: FormControl): { [s: string]: boolean } {
  if (!control.value.match(/^Zime/)) {
    return { invalidUser: true };
  }
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //对应我们登录的表单
  myForm: FormGroup;

  //输入用户名的输入控件
  userName: AbstractControl;
  //输入密码的输入控件
  password: AbstractControl;

  name$: Observable<string>;

  bassUrl = "http://127.0.0.1:8080/xlc";

  s1 = false;
  s2 = true;


  constructor(private fb: FormBuilder, private httpClient: HttpClient) {
    this.myForm = this.fb.group({
      'userName': ['Zimexlc', Validators.compose([Validators.required, userNameValidator, Validators.minLength(3),
      Validators.maxLength(20)])],
      'password': ['123456', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(16)])]
    });

    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
    this.name$ = this.userName.valueChanges;
    this.userName.valueChanges.subscribe(val => {
      console.log(val);
    });
  }
  onSubmit(value: any) {
    console.log(value);
    this.httpClient.post(this.bassUrl, value).subscribe(
      (val: any) => {
        if (val.succ) {
          alert("登录成功！");
          this.s1 = true;
          this.s2 = false;
        } else {
          alert('用户名或密码错误！');
        }
      }
    )
  }
}
